<script setup lang="ts">
import { get, loadFile, post, Message, message, download, formatEnum } from '@/utils'
import NoteModal from './components/NoteModal.vue'
import SendModal from './components/SendModal.vue'
import ViewOrder from './components/ViewOrder.vue'
import ChangeAddress from './components/ChangeAddress.vue'
import useTable from '@/hooks/useTable'
import BatchSendVue from './components/BatchSend.vue'
import useModal from '@/hooks/useModal'
import { OrderStatus, RefundStatus, LogisticsType } from '@/enum/order'
import { Badge } from '@arco-design/web-vue'
import { BtnPermission } from '@/enum/permission'
const { store: batchStore } = useModal()
const { store: viewStore } = useModal()
const { store: sendStore } = useModal()
const { store: noteStore } = useModal()
const { store: addressStore } = useModal()
const selectedKeys = ref([])
const { formatColumns } = useTable()
const searchQuery = reactive({
  sellerId: '',
})
const formRef = ref()
const actionRef = ref()
/**导出 */
const onExcel = () => {
  const query = {
    ids: selectedKeys.value.join(','),
    ...searchQuery,
    ...formRef.value.model,
  }
  if (formRef.value.model?.createTime?.length) {
    query.createTimeBegin = formRef.value.model.createTime?.[0] + ' 00:00:00'
    query.createTimeEnd = formRef.value.model.createTime?.[1] + ' 23:59:59'
  }
  console.log(query)
  download('/server-shop/sys-seller/order/excel', query)
}

const pagination = {
  showPageSize: true,
  pageSize: 20,
}

const request = (params: any, sort: any, filters: any): Promise<any> => {
  return new Promise((resolve, reject) => {
    const query = {
      ...params,
      size: params.pageSize,
      createTimeBegin: params.createTime ? params.createTime[0] + ' 00:00:00' : '',
      createTimeEnd: params.createTime ? params.createTime[1] + ' 23:59:59' : '',
    }
    Reflect.deleteProperty(query, 'pageSize')
    Reflect.deleteProperty(query, 'createTime')
    get(
      {
        url: '/server-shop/sys-seller/order/page',
        data: query,
      },
      ({ data, code }) => {
        data.records.forEach(item => {
          item.orderDetailList.forEach(goods => {
            let _spec = ''
            const specObj = JSON.parse(goods.goods.goodsSpec)
            Object.keys(specObj).forEach(key => {
              _spec += `${key}【${specObj[key]}】 `
            })
            goods.spec = _spec
          })
        })
        resolve({
          data: data.records,
          total: data.total,
          success: code == 200,
        })
      }
    )
  })
}
const columns = formatColumns([
  {
    title: 'id',
    dataIndex: 'id',
    width: 200,
  },
  {
    title: '订单编号',
    dataIndex: 'orderNo',
    hideInSearch: false,
    width: 200,
  },

  {
    title: '商品名称',
    dataIndex: 'goods',
    hideInSearch: false,
    width: 200,
    align: 'left',
    ellipsis: true,
  },

  {
    title: '订单状态',
    dataIndex: 'orderStatus',
    hideInSearch: false,
    valueEnum: {
      [OrderStatus.取消交易]: { text: '取消交易', status: 'normal' },
      [OrderStatus.已完成]: { text: '已完成', status: 'success' },
      [OrderStatus.待付款]: { text: '待付款', status: 'warning' },
      [OrderStatus['待发货/待备货']]: {
        text: '待发货/待备货',
        status: 'processing',
      },
      [OrderStatus['待签收/待自提']]: { text: '待签收/待自提', status: 'processing' },
    },
    render: ({ record }) => {
      // 遍历判断是否部分发货
      const isSectionSend = record.orderDetailList.some(f => f.logisticsNum > 0)
      const valueEnum = {
        [OrderStatus.取消交易]: { text: '取消交易', status: 'normal' },
        [OrderStatus.已完成]: { text: '已完成', status: 'success' },
        [OrderStatus.待付款]: { text: '待付款', status: 'warning' },
        [OrderStatus['待发货/待备货']]: {
          text: isSectionSend ? '部分发货' : '待发货/待备货',
          status: 'processing',
        },
        [OrderStatus['待签收/待自提']]: { text: '待签收/待自提', status: 'processing' },
      }
      const item = valueEnum[record.orderStatus]
      return h(Badge, { status: item.status, text: item.text })
    },

    width: 150,
  },
  {
    title: '评价状态',
    dataIndex: 'commentStatus',
    valueEnum: {
      0: '未评价',
      1: '已评价',
    },
    width: 120,
    hideInSearch: false,
  },

  {
    title: '支付状态',
    dataIndex: 'payStatus',
    width: 100,
    valueEnum: {
      0: { text: '未支付', status: 'Error' },
      1: { text: '已支付', status: 'Success' },
    },
  },
  // {
  //   title: '支付类型',
  //   dataIndex: 'payType',
  //   render: ({ record }) => h('span', {}, '微信支付'),
  //   // valueEnum: formatEnum(PayType),
  //   width: 100,
  // },

  {
    title: '物流类型',
    dataIndex: 'logisticsType',
    hideInSearch: false,
    width: 100,
    valueEnum: formatEnum(LogisticsType),
  },

  {
    title: '收件信息',
    dataIndex: 'addressInfo',
    width: 200,
    children: [
      {
        title: '收件人',
        dataIndex: 'addressName',
        width: 100,
        ellipsis: true,
      },
      {
        title: '联系方式',
        dataIndex: 'addressMobile',
        ellipsis: true,
        width: 150,
      },
      {
        title: '收件地址/自提地址',
        dataIndex: 'address',
        width: 200,
        ellipsis: true,
      },
    ],
  },

  {
    title: '创建时间',
    dataIndex: 'createTime',
    valueType: 'dateRange',
    width: 200,
    hideInSearch: false,
  },
  {
    title: '发货时间',
    dataIndex: 'sendTime',
    width: 200,
  },
  {
    title: '订单备注',
    dataIndex: 'remark',
    width: 120,
    ellipsis: true,
  },
  {
    title: '订单金额',
    width: 100,
    dataIndex: 'goodsPrice',
  },
  {
    title: '实付金额',
    width: 100,
    dataIndex: 'orderPrice',
  },
  {
    title: '平台优惠券抵扣',
    dataIndex: 'deductCouponSystem',
    width: 170,
  },
  {
    title: '商户优惠券抵扣',
    dataIndex: 'deductCouponSeller',
    width: 170,
  },
  {
    title: '积分抵扣',
    dataIndex: 'deductIntegral',
    width: 120,
  },
  {
    title: '余额抵扣',
    dataIndex: 'deductMoney',
    width: 120,
  },
  {
    title: '活动抵扣',
    dataIndex: 'deductPublicity',
    width: 120,
  },
  {
    title: '操作',
    dataIndex: 'operations',
    width: 400,
    fixed: 'right',
    slotName: 'operations',
    btnList: [
      {
        permission: BtnPermission.查看,
        name: '查看',
        handle: ({ record }) => viewStore.handleShow(record),
      },
      {
        name: '备注',
        permission: BtnPermission.编辑,
        disabled: ({ record }) => record.orderStatus != OrderStatus.待付款,
        handle: ({ record }) => noteStore.handleShow(record),
      },

      {
        permission: BtnPermission.编辑,
        name: '发货',
        disabled: ({ record }) => {
          if (record.refundStatus == RefundStatus.全售后) return true
          return record.orderStatus != OrderStatus['待发货/待备货']
        },
        hidden: ({ record }) => LogisticsType.自提 == record.logisticsType,
        handle: ({ record }) => sendStore.handleShow(record),
      },
      {
        name: '备货',
        permission: BtnPermission.编辑,
        disabled: ({ record }) => {
          if (record.refundStatus == RefundStatus.全售后) return true
          return record.orderStatus != OrderStatus['待发货/待备货']
        },
        hidden: ({ record }) => LogisticsType.快递 == record.logisticsType,
        type: 'popconfirm',
        tip: '确认该订单已经备货完成吗',
        handle: ({ record }) => {
          post({ url: '/server-shop/sys-seller/order/logistics/save', data: { orderId: record.id, type: 1, logisticsType: 0 } }, ({ code, msg }) => {
            actionRef.value.reload()
            message({
              type: code == 200 ? 'success' : 'error',
              content: msg,
            })
          })
        },
      },
      {
        name: '核销',
        permission: BtnPermission.编辑,
        disabled: ({ record }) => {
          if (record.refundStatus == RefundStatus.全售后) return true
          if (record.logisticsType == LogisticsType.快递) return true
          if (record.orderStatus != OrderStatus['待签收/待自提']) return true
          else return record.orderStatus != OrderStatus['待签收/待自提']
        },
        type: 'popconfirm',
        tip: '确认核销该笔订单吗',
        handle: ({ record }) => {
          post({ url: '/server-shop/sys-seller/order/finish', data: { id: record.id } }, ({ code, msg }) => {
            if (code == 200) actionRef.value.reload()
            message({
              type: code === 200 ? 'success' : 'error',
              content: msg,
            })
          })
        },
      },
      {
        name: '修改收货地址',
        permission: BtnPermission.编辑,
        disabled: ({ record }) => ![OrderStatus['待发货/待备货'], OrderStatus.待付款].includes(record.orderStatus),
        handle: ({ record }) => addressStore.handleShow(record),
      },
    ],
  },
])
const batchSend = () => {
  if (selectedKeys.value.length) {
    batchStore.handleShow({ id: selectedKeys.value })
  } else {
    message({
      type: 'warning',
      content: '至少选择一条数据后操作！',
    })
  }
}
</script>

<template>
  <div class="page">
    <ProTable
      :columns="columns"
      :request="request"
      row-key="id"
      :form-ref="ref => (formRef = ref)"
      :pagination="pagination"
      header-title=" "
      column-resizable
      :params="searchQuery"
      :scroll="{ x: 1000 }"
      :bordered="{ cell: true }"
      :action-ref="ref => (actionRef = ref)"
      v-model:selectedKeys="selectedKeys"
      @reset="() => (searchQuery.sellerId = '')"
      :row-selection="{
        type: 'checkbox',
        showCheckedAll: true,
        onlyCurrent: false,
      }"
    >
      <template #option-render="{ dom, reset }">
        <component :is="dom[1]" />
        <component :is="dom[0]" />
      </template>
      <template #tool-bar>
        <a-button type="primary" @click="onExcel" class="mb10" v-permission="[BtnPermission.查看]">
          <template #icon>
            <icon-download />
          </template>
          导出订单
        </a-button>
        <a-button type="primary" @click="batchSend" class="mb10" v-permission="[BtnPermission.编辑]">
          <template #icon>
            <icon-select-all />
          </template>
          批量发货
        </a-button>
      </template>

      <template #goods="{ record }">
        <a-space direction="vertical">
          <div class="flex" v-for="item in record.orderDetailList">
            <a-image width="50" :src="item.goods.img" />
            <div>
              <p>{{ item.goods.name }}</p>
              <p>{{ item.spec }}</p>
              <p>{{ item.goods.sn }}</p>
            </div>
          </div>
        </a-space>
      </template>
      <template #addressName="{ record }">
        <p class="name mr10">{{ record.logistics.consignee || '-' }}</p>
      </template>
      <template #addressMobile="{ record }">
        <p class="name mr10">{{ record.logistics?.mobile || '-' }}</p>
      </template>
      <template #address="{ record }">
        <span v-if="record.logisticsType != LogisticsType.自提">
          {{ record.logistics?.province }}
          {{ record.logistics?.city }}
          {{ record.logistics?.district }}
          {{ record.logistics?.address }}
        </span>
        <span v-else>
          {{ record.seller.extVO?.pickAddress }}
        </span>
      </template>
    </ProTable>
    <ViewOrder v-if="viewStore.show" v-model:show="viewStore.show" :id="viewStore.id" />
    <SendModal v-if="sendStore.show" v-model:show="sendStore.show" :id="sendStore.id" @confirm="actionRef.reload" :type="sendStore.info.logisticsType" />
    <NoteModal v-if="noteStore.show" v-model:show="noteStore.show" :id="noteStore.id" @confirm="actionRef.reload" />
    <BatchSendVue v-if="batchStore.show" v-model:show="batchStore.show" :id="batchStore.id" @confirm="actionRef.reload" />
    <ChangeAddress v-if="addressStore.show" v-model:show="addressStore.show" :id="addressStore.id" :userId="addressStore.info.userId" :address-id="addressStore.info.logistics.id" @confirm="actionRef.reload" />
  </div>
</template>
<style scoped lang="less">
.img {
  width: 40px;
}
.container {
  padding: 0 20px 20px 20px;
}
:deep(.arco-table-th) {
  &:last-child {
    .arco-table-th-item-title {
      margin-left: 16px;
    }
  }
}
.action-icon {
  margin-left: 12px;
  cursor: pointer;
}
.active {
  color: #0960bd;
  background-color: #e3f4fc;
}
.setting {
  display: flex;
  align-items: center;
  width: 200px;
  .title {
    margin-left: 12px;
    cursor: pointer;
  }
}
</style>
